<script lang="ts" setup>
import type { LowcodeDatasourceApi } from '#/api/lowcode/datasource';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Icon } from '@iconify/vue';

import { getDatasourceHealth, testDatasourceConnection } from '#/api/lowcode/datasource';

const emit = defineEmits(['success']);
const testing = ref(false);
const testResult = ref<LowcodeDatasourceApi.ConnectionTestResult>();
const healthInfo = ref<LowcodeDatasourceApi.HealthCheckResult>();
const datasourceConfig = ref<LowcodeDatasourceApi.DatasourceConfig>();

const [Modal, modalApi] = useVbenModal({
  title: '连接测试',
  width: '600px',
  onCancel() {
    modalApi.close();
  },
});

defineExpose({
  modalApi,
});

// 测试连接
async function handleTestConnection() {
  if (!datasourceConfig.value) {
    return;
  }

  try {
    testing.value = true;
    testResult.value = undefined;
    healthInfo.value = undefined;

    testResult.value = await testDatasourceConnection(datasourceConfig.value);

    // 如果测试成功且有ID，获取健康状态
    if (testResult.value?.success && datasourceConfig.value.id) {
      try {
        healthInfo.value = await getDatasourceHealth(datasourceConfig.value.id);
      } catch (error) {
        console.warn('获取健康状态失败:', error);
      }
    }
  } catch (error: any) {
    console.error('数据源连接测试失败:', error);
    
    let errorMessage = '连接测试失败';
    if (error?.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error?.message) {
      errorMessage = error.message;
    }
    
    testResult.value = {
      success: false,
      message: errorMessage,
    };
  } finally {
    testing.value = false;
  }
}

modalApi.onOpenChange = async (isOpen: boolean, data?: LowcodeDatasourceApi.DatasourceConfig) => {
  if (isOpen) {
    datasourceConfig.value = data;
    testResult.value = undefined;
    healthInfo.value = undefined;
  }
};
</script>

<template>
  <Modal>
    <a-space direction="vertical" style="width: 100%">
      <!-- 连接测试按钮 -->
      <a-button
        type="primary"
        :loading="testing"
        @click="handleTestConnection"
        style="margin-bottom: 16px"
      >
        <template #icon>
          <Icon icon="ant-design:link-outlined" />
        </template>
        测试连接
      </a-button>

      <!-- 测试结果 -->
      <a-alert
        v-if="testResult"
        :type="testResult.success ? 'success' : 'error'"
        show-icon
      >
        <template #message>
          <span>{{ testResult.success ? '连接测试成功' : '连接测试失败' }}</span>
          <span v-if="testResult.responseTime" style="margin-left: 8px; color: #666;">
            ({{ testResult.responseTime }}ms)
          </span>
        </template>
        <template #description>
          {{ testResult.message }}
        </template>
      </a-alert>

      <!-- 健康检查信息 -->
      <a-card
        v-if="healthInfo && testResult?.success"
        title="连接池状态"
        size="small"
        style="margin-top: 16px"
      >
        <a-descriptions :column="2" size="small">
          <a-descriptions-item label="健康状态">
            <a-badge 
              :status="healthInfo.healthy ? 'success' : 'error'"
              :text="healthInfo.healthy ? '健康' : '异常'"
            />
          </a-descriptions-item>
          <a-descriptions-item label="活跃连接数">
            {{ healthInfo.activeConnections }}
          </a-descriptions-item>
          <a-descriptions-item label="空闲连接数">
            {{ healthInfo.idleConnections }}
          </a-descriptions-item>
          <a-descriptions-item label="最大连接数">
            {{ healthInfo.maxConnections }}
          </a-descriptions-item>
          <a-descriptions-item v-if="healthInfo.details" label="详细信息" :span="2">
            {{ healthInfo.details }}
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
    </a-space>
  </Modal>
</template>